package cn.iocoder.yudao.module.member.service.usercommission;

import org.springframework.stereotype.Service;

@Service
public class CommissionService {

    private static final Integer RECHARGE_STEP_1 = 1000000;
    private static final Double COMMISSION_RATIO_STEP_1 = 0.15;

    private static final Integer RECHARGE_STEP_2 = 5000000;
    private static final Double COMMISSION_RATIO_STEP_2 = 0.2;

    private static final Double COMMISSION_RATIO_STEP_3 = 0.25;

    // 固定比例
    private static final Double COMMISSION_FIXED_RATIO = 0.1;

    /**
     * 计算阶梯佣金
     *
     * @param totalRecharge 当前累计充值
     * @param recharge      新充值
     * @return
     */
    public Integer calculateStepCommission(double totalRecharge, double recharge) {
        double newTotalRecharge = totalRecharge + recharge;

        if (newTotalRecharge <= RECHARGE_STEP_1) {
            return (int) Math.floor(recharge * COMMISSION_RATIO_STEP_1);
        }

        if (newTotalRecharge <= RECHARGE_STEP_2) {
            if (totalRecharge < RECHARGE_STEP_1) {
                double commission = 0;
                double paddingUnderStep1 = RECHARGE_STEP_1 - totalRecharge;
                commission += paddingUnderStep1 * COMMISSION_RATIO_STEP_1;
                commission += (recharge - paddingUnderStep1) * COMMISSION_RATIO_STEP_2;
                return (int) Math.floor(commission);
            } else {
                return (int) Math.floor(recharge * COMMISSION_RATIO_STEP_2);
            }
        }

        if (totalRecharge < RECHARGE_STEP_1) {
            double commission = 0;
            double paddingUnderStep1 = RECHARGE_STEP_1 - totalRecharge;
            commission += paddingUnderStep1 * COMMISSION_RATIO_STEP_1;

            double paddingUnderStep2 = RECHARGE_STEP_2 - RECHARGE_STEP_1;
            commission += paddingUnderStep2 * COMMISSION_RATIO_STEP_2;

            commission += (recharge - paddingUnderStep2 - paddingUnderStep1) * COMMISSION_RATIO_STEP_3;

            return (int) Math.floor(commission);
        } else if (totalRecharge < RECHARGE_STEP_2) {
            double commission = 0;
            double paddingUnderStep2 = RECHARGE_STEP_2 - totalRecharge;
            commission += paddingUnderStep2 * COMMISSION_RATIO_STEP_2;
            commission += (recharge - paddingUnderStep2) * COMMISSION_RATIO_STEP_3;
            return (int) Math.floor(commission);
        } else {
            return (int) Math.floor(recharge * COMMISSION_RATIO_STEP_3);
        }
    }

    /**
     * 计算固定比例的佣金
     *
     * @param recharge 充值金额
     * @return 佣金
     */
    public Integer calculateFixedRatioCommission(Integer recharge) {
        return (int) Math.floor(recharge * COMMISSION_FIXED_RATIO);
    }

}
